package com.lxq.market.servlet;

import com.lxq.market.model.User;
import com.lxq.market.service.UserService;
import com.lxq.market.util.SessionSignIn;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    UserService service=UserService.getInstance();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userAccount = req.getParameter("user_account");
        String userPassword = req.getParameter("user_password");
        User user = service.getUser(userAccount);
//        JsonObject jsonObject=new JsonObject();
        if (user==null){
//            jsonObject.addProperty("code",-1);
//            jsonObject.addProperty("because","不存在该账户");
            req.setAttribute("unsuccessfully_login_result","登录失败，不存在该账户");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }else if (!user.getUserPassword().equals(userPassword)){
//            jsonObject.addProperty("code",-2);
//            jsonObject.addProperty("because","密码错误");
            req.setAttribute("unsuccessfully_login_result","登录失败，密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }else if(user.getUserPosition().equals("冻结")){
            req.setAttribute("unsuccessfully_login_result","登录失败，该账号已被冻结");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }
        SessionSignIn.getInstance().addSign(req.getSession().getId(),user);
        String nextUrl=req.getParameter("interrupted")!=null? req.getParameter("interrupted") :"/index";
        resp.sendRedirect(nextUrl);
    }
}
